package com.csun.cmny.security.core.authentication;

import com.csun.cmny.security.core.properties.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-10-22 17:22
 * @Description:
 */
public class HuaLongAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String POST = "POST";
    private boolean postOnly = true;

    /**
     * 配置自定义华隆登录接口
     */
    public HuaLongAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.HUA_LONG_SIGN_IN_PROCESSING_URL_MOBILE, "POST"));
    }

    /**
     * Attempt authentication authentication.
     *
     * @param request  the request
     * @param response the response
     *
     * @return the authentication
     *
     * @throws AuthenticationException the authentication exception
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (postOnly && !POST.equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String account = request.getParameter(SecurityConstants.HUA_LONG_PARAMETER_NAME_ACCOUNT);
        String password = request.getParameter(SecurityConstants.HUA_LONG_PARAMETER_NAME_PASSWORD);
        String role = request.getParameter(SecurityConstants.HUA_LONG_PARAMETER_NAME_ROLE);

        if (account == null) {
            account = "";
        }
        account = account.trim();

        if (password == null) {
            password = "";
        }
        password = password.trim();

        if (role == null) {
            role = "";
        }
        role = role.trim();

        HuaLongAuthenticationToken authRequest = new HuaLongAuthenticationToken(account, password, role);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request, HuaLongAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
